#include "preHeader.h"
#include "Session/MapServerPacketHandler.h"
#include "Session/PacketDispatcher.h"
#include "Session/GameServerMgr.h"
#include "Map/InstanceMgr.h"

int MapServerPacketHandler::HandleStartInstance(MapServerService* pService, INetPacket& pck)
{
	InstGUID fakeInstGuid;
	ObjGUID instOwner;
	uint32 opCodeResp, flags;
	pck >> fakeInstGuid >> instOwner >> opCodeResp >> flags;
	sInstanceMgr.StartInstance(
		fakeInstGuid, instOwner, flags, pck.CastReadableStringView(),
		[=](bool isSucc, InstGUID instGuid) {
		if (opCodeResp != OPCODE_NONE) {
			NetPacket resp(opCodeResp);
			resp << isSucc << flags << instGuid << fakeInstGuid;
			sPacketDispatcher.SendPacket2CrossServer(resp);
		}
	});
	return SessionHandleSuccess;
}

int MapServerPacketHandler::HandleStopInstance(MapServerService* pService, INetPacket& pck)
{
	InstGUID instGuid;
	pck >> instGuid;
	sInstanceMgr.StopInstance(instGuid);
	return SessionHandleSuccess;
}

int MapServerPacketHandler::HandleQueryPlayerLevelMax(MapServerService* pService, INetPacket& pck, const RPCActor::RequestMetaInfo& info)
{
	uint32 playerLevelMax = 0;
	for (size_t i = 0, n = NGSSession(); i < n; ++i) {
		playerLevelMax = std::max(
			playerLevelMax, GSSession(i).getCData().GetPlayerLevelMax());
	}
	NetPacket rpcRespPck(CMC_RPC_INVOKE_RESP);
	rpcRespPck << playerLevelMax;
	sPacketDispatcher.RPCReply(rpcRespPck, info.sn);
	return SessionHandleSuccess;
}
